package com.huanqi.tpapi;

import static com.huanqi.tpapi.TPSeekListener.STOPPED;

import com.huanqi.hqw.Utils.HQWLogUtil;
import com.huanqi.hqw.Utils.HQWTimeUtil;
import com.huanqi.tpapi.cybergarage.upnp.Action;
import com.huanqi.tpapi.cybergarage.upnp.ControlPoint;
import com.huanqi.tpapi.cybergarage.upnp.Device;
import com.huanqi.tpapi.cybergarage.upnp.Service;
import com.huanqi.tpapi.cybergarage.upnp.device.DeviceChangeListener;
import com.huanqi.tpapi.cybergarage.upnp.event.EventListener;


import java.util.Timer;
import java.util.TimerTask;

public class TPMovieApi {



    public final static int AddDevice = 5;//添加设备
    public final static int RemoveDevice = 6;//删除设备

    public final static int TPBACK = 7;

    public static int TPSTATE = STOPPED;

    ControlPoint controlPoint;

    Timer seekTimer;
    Timer stateTimer;

    TPSeekListener tpSeekListener;

    public void setTpSeekListener(TPSeekListener tpSeekListener) {
        this.tpSeekListener = tpSeekListener;
    }


    public void oncreate() {
        new Thread(new Runnable() {
            public void run() {
                controlPoint = new ControlPoint();
                controlPoint.start();
                controlPoint.search();
                controlPoint.addDeviceChangeListener(new DeviceChangeListener() {
                    @Override
                    public void deviceAdded(Device device) {
                        //判断是否为DMR
                        if ("urn:schemas-upnp-org:device:MediaRenderer:1".equals(device.getDeviceType())) {
                            tpSeekListener.TPDeviceMessage(device, TPMovieApi.AddDevice);
                        }
                    }

                    @Override
                    public void deviceRemoved(Device device) {
                        //判断是否为DMR
                        if ("urn:schemas-upnp-org:device:MediaRenderer:1".equals(device.getDeviceType())) {
                            tpSeekListener.TPDeviceMessage(device, TPMovieApi.RemoveDevice);
                        }
                    }
                });
            }
        }).start();
    }



    public void clean() {
        remoteSeekListener();
        remoteStateListener();
        new Thread(new Runnable() {
            public void run() {
                if (controlPoint != null) {
                    controlPoint.stop();
                }
            }
        }).start();
    }

    public void setseek(Service service, int Progress) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Action transportAction = service.getAction("Seek");//行动
                transportAction.setArgumentValue("InstanceID", 0);
                transportAction.setArgumentValue("Unit", "REL_TIME");
                String[] time = HQWTimeUtil.ValueForTime(Progress).split(":");
                String timeint = "";
                if (time.length < 3) {
                    timeint = "00:" + HQWTimeUtil.ValueForTime(Progress);
                    transportAction.setArgumentValue("Target", timeint);
                } else {
                    transportAction.setArgumentValue("Target", "" + HQWTimeUtil.ValueForTime(Progress));
                }
                if (transportAction.postControlAction()) {
                    HQWLogUtil.logi("TPAPI,投屏事件进度改变", "成功" + transportAction.getStatus().getDescription());
                } else {
                    tpSeekListener.TPEventMessage("投屏事件进度改变失败");
                    HQWLogUtil.logi("TPAPI,投屏事件进度改变", "失败" + transportAction.getStatus().getDescription());
                }
            }
        }).start();
    }

    public void play(Service service) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Action transportAction = service.getAction("Play");//行动
                transportAction.setArgumentValue("InstanceID", 0);
                transportAction.setArgumentValue("Speed", 1);
                if (transportAction.postControlAction()) {
                    HQWLogUtil.logi("TPAPI,投屏事件播放", "成功" + transportAction.getStatus().getDescription());
                } else {
                    HQWLogUtil.logi("TPAPI,投屏事件播放", "失败" + transportAction.getStatus().getDescription());
                    tpSeekListener.TPEventMessage("投屏事件播放失败");
                }
            }
        }).start();
    }

    public void pause(Service service) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Action transportAction = service.getAction("Pause");//行动
                transportAction.setArgumentValue("InstanceID", 0);
                if (transportAction.postControlAction()) {
                    HQWLogUtil.logi("TPAPI,投屏事件暂停", "成功" + transportAction.getStatus().getDescription());
                } else {
                    HQWLogUtil.logi("TPAPI,投屏事件暂停", "失败" + transportAction.getStatus().getDescription());
                    tpSeekListener.TPEventMessage("投屏事件暂停失败");
                }
            }
        }).start();
    }

    public void stop(Service service) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Action transportAction = service.getAction("Stop");//行动
                transportAction.setArgumentValue("InstanceID", 0);
                if (transportAction.postControlAction()) {
                    HQWLogUtil.logi("TPAPI,投屏事件停止", "成功" + transportAction.getStatus().getDescription());
                } else {
                    HQWLogUtil.logi("TPAPI,投屏事件停止", "失败" + transportAction.getStatus().getDescription());
                    tpSeekListener.TPEventMessage("投屏事件停止失败");
                }
            }
        }).start();
    }

    public void startTP(Service service, String name, String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Action transportAction = service.getAction("SetAVTransportURI");//行动
                transportAction.setArgumentValue("InstanceID", 0);
                transportAction.setArgumentValue("CurrentURI", url);
                transportAction.setArgumentValue("CurrentURIMetaData", name);
                if (transportAction.postControlAction()) {
                    HQWLogUtil.logi("TPAPI,投屏事件开始投屏", "成功" + transportAction.getStatus().getDescription());
                } else {
                    HQWLogUtil.logi("TPAPI,投屏事件开始投屏", "失败" + transportAction.getStatus().getDescription());
                    tpSeekListener.TPEventMessage("投屏事件开始投屏失败");
                }

            }
        }).start();
    }

    public void addSeekListener(Service service) {
        remoteSeekListener();
        seekTimer = new Timer();
        seekTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    Action transportAction = service.getAction("GetPositionInfo");
                    transportAction.setArgumentValue("InstanceID", 0);

                    Action transportAction2 = service.getAction("GetMediaInfo");
                    transportAction2.setArgumentValue("InstanceID", 0);

                    if (transportAction.postControlAction() && transportAction2.postControlAction()) {
                        String[] time = transportAction.getArgumentValue("RelTime").split(":");
                        String[] timemax = transportAction.getArgumentValue("TrackDuration").split(":");
                        int seek = Integer.valueOf(time[0]) * 60 * 60 * 1000 + Integer.valueOf(time[1]) * 60 * 1000 + Integer.valueOf(time[2]) * 1000;
                        int max = Integer.valueOf(timemax[0]) * 60 * 60 * 1000 + Integer.valueOf(timemax[1]) * 60 * 1000 + Integer.valueOf(timemax[2]) * 1000;

                        String name = transportAction2.getArgumentValue("CurrentURIMetaData");
                        tpSeekListener.TPSeekMessage(name, seek, max);
                    } else {
                        HQWLogUtil.logi("TPAPI,设备进度监听", "失败" + transportAction.getStatus().getDescription());
                        tpSeekListener.TPEventMessage("设备进度监听失败");
                    }
                } catch (Exception V) {
                }
            }
        }, 0, 1000);
    }

    public void remoteSeekListener() {
        if (seekTimer != null) {
            seekTimer.cancel();
        }
    }

    public void addStateListener(Service service) {
        remoteStateListener();
        stateTimer = new Timer();
        stateTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    Action transportAction = service.getAction("GetTransportInfo");
                    transportAction.setArgumentValue("InstanceID", 0);

                    if (transportAction.postControlAction()) {
                        String state = transportAction.getArgumentValue("CurrentTransportState");
                        switch (state){
                            case "PAUSED_PLAYBACK":
                                TPSTATE = TPSeekListener.PAUSED_PLAYBACK;
                                tpSeekListener.TPState(TPSeekListener.PAUSED_PLAYBACK);
                                break;
                            case "PLAYING":
                                TPSTATE = TPSeekListener.PLAYING;
                                tpSeekListener.TPState(TPSeekListener.PLAYING);
                                break;
                            case "STOPPED":
                                TPSTATE = TPSeekListener.STOPPED;
                                tpSeekListener.TPState(TPSeekListener.STOPPED);
                                break;
                            case "TRANSITIONING":
                                TPSTATE = TPSeekListener.TRANSITIONING;
                                tpSeekListener.TPState(TPSeekListener.TRANSITIONING);
                                break;
                            case "NO_MEDIA_PRESENT":
                                TPSTATE = TPSeekListener.NO_MEDIA_PRESENT;
                                tpSeekListener.TPState(TPSeekListener.NO_MEDIA_PRESENT);
                                break;
                        }
                    } else {
                        HQWLogUtil.logi("TPAPI,设备状态监听", "失败" + transportAction.getStatus().getDescription());
                        tpSeekListener.TPEventMessage("设备状态监听失败");
                    }
                } catch (Exception V) {
                }
            }
        }, 0, 1000);
    }

    public void remoteStateListener() {
        if (stateTimer != null) {
            stateTimer.cancel();
        }
    }

    public Service DevicetoService(Device device) {
        return device.getService("urn:schemas-upnp-org:service:AVTransport:1");
    }

}
